#include "AnaDef.h"
#include "XGLUtils.h"

void getpar(const TString fin, const Int_t itype)
{
  TFile *ff=new TFile(fin);
  if(!ff->IsOpen()){
    printf("file not open %s\n", fin.Data());exit(1);
  }

  TTree * tt = (TTree*) ff->Get("tree");
  if(!tt){
    printf("no tree!\n"); ff->ls(); exit(1);
  }

  TList *ll = new TList;

  TH2D *hh=new TH2D("hh","",100,0,5,200,-10,10); ll->Add(hh);

  //type 1, 2, 4: electron, pion, proton
  //pid 0, 2, 4
  tt->Draw(Form("sigmaTRD%d:pTRD>>hh", itype==1?0:itype),Form("pidV0==%d",itype));

  const Double_t thres = 50;

  TH2D *hnor = XGLUtils::NormalHist(hh, thres); ll->Add(hnor);

  TH1D *hamp=0x0;
  TH1D *hmpv=0x0;
  TH1D* hwid=0x0;
  TH1D* hchi=0x0;
  TH1D* hres=0x0;

  TList * lslice = new TList;

  XGLUtils::FitSlicesY(hh, XGLUtils::RawGaus, hamp, hmpv, hwid, hres, hchi,thres, -999,-999, lslice);

  ll->Add(hamp);  ll->Add(hmpv);  ll->Add(hwid);  ll->Add(hchi);  ll->Add(hres);

  TFile *fout=new TFile(Form("outputana%d.root", itype),"recreate");
  ll->Write();
  lslice->Write();
  fout->Save();
  fout->Close();
  delete fout;
}

int main(int argc, char* argv[])
{
  for(int ii=0; ii<argc; ii++){
    printf("%d: %s\n", ii, argv[ii]);
  }

  if(argc!=3){
    printf("argc!=2\n");return 1;
  }


  getpar(argv[1], atoi(argv[2]));

  return 0;
}
